/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>Project: smvc2022 - WebConfig
 * <p>Powered by webrx On 2022-03-18 14:58:24
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@Configuration
@EnableWebMvc
@ComponentScan("cn.webrx.controller")
@RestController
public class WebConfig implements WebApplicationInitializer, WebMvcConfigurer {
    @Override
    public void onStartup(ServletContext c) throws ServletException {
        var ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(this.getClass());
        ctx.setServletContext(c);
        ServletRegistration.Dynamic servlet = c.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //-------------配置当前springmvc 项目的消息转换器
        var shmc = new StringHttpMessageConverter();
        shmc.setDefaultCharset(StandardCharsets.UTF_8);
        var list = List.of(MediaType.parseMediaType("text/html;charset=UTF-8"));
        shmc.setSupportedMediaTypes(list);
        converters.add(shmc);
    }

    @RequestMapping
    public String home(){
        return "hello world springmvc - 中文字符串";
    }
}
